package controllers

import (
	"film/models"
	"film/pkg"
	beego "github.com/beego/beego/v2/server/web"
	"time"
)

type UserController struct {
	beego.Controller
}

type JsonR struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func (c *UserController) Login() {
	username := c.GetString("username")
	password := c.GetString("password")
	key := "lock-" + username
	count, _ := models.Rdb.Get(key).Int()
	if count >= 3 {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "账号已经锁定请等待15分钟",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	var user models.User
	err := models.DB.Model(&models.User{}).Where("username=?", username).First(&user).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "用户不存在",
			Data: nil,
		}
		c.ServeJSON()
		return
	}
	if user.Password == pkg.MD5Password(password) {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "登录成功",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		models.Rdb.Incr(key)
		models.Rdb.Expire(key, time.Minute*15)
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "密码错误,登录失败",
			Data: nil,
		}
		c.ServeJSON()
	}
}

func (c *UserController) Zc() {
	username := c.GetString("username")
	password := c.GetString("password")
	user := models.User{
		Username: username,
		Password: pkg.MD5Password(password),
	}
	err := models.DB.Create(&user).Error
	if err != nil {
		c.Data["json"] = JsonR{
			Code: 500,
			Msg:  "注册失败",
			Data: nil,
		}
		c.ServeJSON()
		return
	} else {
		c.Data["json"] = JsonR{
			Code: 200,
			Msg:  "注册成功",
			Data: nil,
		}
		c.ServeJSON()
	}
}
